//
//  oAuthViewController.swift
//  SinaWeiBo
//
//  Created by tuyue on 16/3/8.
//  Copyright © 2016年 xueyang.co.ltd. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class oAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAccount(){
        /**在webView中设置账号和密码*/
        let jsString = "document.getElementById('userId').value = '532560728@qq.com',document.getElementById('passwd').value = '369589'"
        /**在webView中执行JavaScript代码*/
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        /**手动创建的根视图控制器是透明的，就把背景颜色改为白色*/
        view.backgroundColor = UIColor.whiteColor()
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        
        /**设置登录界面的navBar*/
        setAboutoAuthNavBar()
        /**调取加载授权界面*/
        loadOAuthPage()
    }
    
    //MARK: - 解决退出时SVP动画还在转动的bug
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
    
    //MARK: - 加载授权界面
    func loadOAuthPage(){
        /**urlString*/
        let urlString = "https://api.weibo.com/oauth2/authorize?"+"client_id=\(client_id)"+"&redirect_uri=\(redirect_uri)"
        /**NSURL*/
        let url = NSURL(string: urlString)
        /**NSURLRequest*/
        let urlRequest = NSURLRequest(URL: url!)
        /**webView加载请求*/
        webView.loadRequest(urlRequest)
    }
    
    //MARK: - 设置导航条
    func setAboutoAuthNavBar(){
        /**设置导航条左键*/
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试界面", style: .Plain, target: self, action: "defaultAccount")
    }
}


//MARK: - 创建webView代理类，来进行设置等待指示器的状态
extension oAuthViewController: UIWebViewDelegate {
    
    /**webView开始加载的方法*/
    func webViewDidStartLoad(webView: UIWebView) {
        /**调取SVP中等待指示器*/
        SVProgressHUD.show()
        
    }
    /**webView加载完成的方法*/
    func webViewDidFinishLoad(webView: UIWebView) {
        /**让等待指示器消失的方法*/
        SVProgressHUD.dismiss()
    }
    
    //MARK: - webView加载请求数据
    /**webView加载请求数据*/
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.URL)
        
        /**判断request.URL是否包含一个绝对路径，没有就返回false*/
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        /**判断返回的URL中是否包含code,获取code方法*/
        if urlString.containsString("code"){
            guard let qurey = request.URL?.query else {
                return false
            }
            //            print(qurey)
            let codeStr = "code="
            let code = (qurey as NSString).substringFromIndex(codeStr.characters.count)
            UserAccount.sharedAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                /**登录成功，销毁当前页面*/
                self.close()
//   用通知的方式代替当前这种方式去设置控制器Window的跟控制器             UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "oauth")
            })
    
            //            print(qurey,code)
            return false
        }
        return true
    }
    
    

    
}
